﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BucaUtils
{
    public class TextHelper
    {
        public static string GetHtmlTemplate(string tempPath, List<KeyValuePair<string, string>> keyValueReplace)
        {
            try
            {
                var filepath = HttpContext.Current.Server.MapPath(tempPath);
                var strHtml = new StringBuilder();
                strHtml.Append(ReadFileContent(filepath));
                strHtml = keyValueReplace.Aggregate(strHtml, (current, pair) => current.Replace(pair.Key, pair.Value));
                return strHtml.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }
        private static string ReadFileContent(string filepath)
        {
            var strHtml = new StringBuilder();
            try
            {
                if (File.Exists(filepath))
                {
                    StreamReader reader = null;
                    try
                    {
                        reader = new StreamReader(filepath);
                        strHtml.Append(reader.ReadToEnd());
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
            return strHtml.ToString();
        }

    }
}
